﻿@page "/authentication/changePassword"
@inherits BasePage
@attribute [Authorize]
@inject IOptions<ServerSettings> ServerSettings
@inject MessageService MessageService

<PageContainer Title="Change Password" PageTitle="@Title">
    <Breadcrumb>
        <Breadcrumb>
            <BreadcrumbItem>
                <a href="">
                    <MdiIcon Type="@IconNames.Home" />
                    <span>Home</span>
                </a>
            </BreadcrumbItem>
            <BreadcrumbItem>
                <span>
                    <MdiIcon Type="@IconNames.ChangePassword" />
                    <span>Change Password</span>
                </span>
            </BreadcrumbItem>
        </Breadcrumb>
    </Breadcrumb>
    <ChildContent>
        <Form Model="@model"
              OnFinish="OnSubmit">
            <FormItem Label="User Name">
                <Input @bind-Value="@context.Username" />
            </FormItem>
            <FormItem Label="Old Password">
                <InputPassword @bind-Value="@context.Password" />
            </FormItem>
            <FormItem Label="New Password">
                <InputPassword @bind-Value="@context.NewPassword" />
            </FormItem>
            <FormItem>
                <Button Type="@ButtonType.Primary" HtmlType="submit">
                    Change Password
                </Button>
            </FormItem>
        </Form>
    </ChildContent>
</PageContainer>

@code{
    class Model
    {
        [Required]
        public string Username { get; set; }
        [Required]
        public string Password { get; set; }

        [Required]
        public string NewPassword { get; set; }
    }

    private Model model = new Model();

    protected override void OnInitialized()
    {
        Title = "Change Password";
        base.OnInitialized();
    }

    async Task OnSubmit()
    {
        try
        {
            var success = await Service.UserService.ChangePassword(new Services.Models.UserChangePasswordRequest
            {
                LoginRequest = new Services.Models.UserLoginRequest
                {
                    UserName = model.Username,
                    Password = model.Password,
                },
                NewPassword = model.NewPassword,
            });
            if (success)
            {
                _ = MessageService.Success($"Change password successfully");
            }
            else
            {
                await MessageService.Error($"Failed to change password.");
            }
        }
        catch
        {
            await MessageService.Error($"Failed to change password.");
        }
    }
}
